/**
 * 清理重复的训练记录脚本
 */

const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: '43.143.253.188',
  user: 'nextjs',
  password: 'yEAiRE2jcxTyRBy5',
  database: 'nextjs',
  charset: 'utf8mb4'
};

async function cleanupTrainingRecords () {
  let connection;

  try {
    console.log('🔌 连接数据库...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功');

    // 查看当前训练记录
    console.log('🔍 查看当前训练记录...');
    const [rows] = await connection.execute(
      'SELECT id, characterId, characterMountId, trainingDate, dailyCount, totalExperience FROM mount_training WHERE characterId = 2001 ORDER BY id'
    );

    console.log('📊 当前训练记录:');
    rows.forEach((record, index) => {
      console.log(`  ${index + 1}. ID: ${record.id}, 角色: ${record.characterId}, 坐骑: ${record.characterMountId}, 日期: ${record.trainingDate}, 次数: ${record.dailyCount}, 总经验: ${record.totalExperience}`);
    });

    // 删除所有训练记录
    console.log('🗑️ 删除所有训练记录...');
    await connection.execute('DELETE FROM mount_training WHERE characterId = 2001');
    console.log('✅ 训练记录已清理');

    // 验证清理结果
    console.log('🔍 验证清理结果...');
    const [newRows] = await connection.execute(
      'SELECT COUNT(*) as count FROM mount_training WHERE characterId = 2001'
    );

    console.log(`📊 清理后训练记录数量: ${newRows[0].count}`);

    console.log('🎉 训练记录清理完成！');

  } catch (error) {
    console.error('❌ 清理训练记录失败:', error.message);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 运行脚本
if (require.main === module) {
  cleanupTrainingRecords().catch((error) => {
    console.error('💥 脚本执行失败:', error.message);
    process.exit(1);
  });
}

module.exports = { cleanupTrainingRecords };
